#include <webx/route.h>
#include <webx/route.h>

class ExportEntity : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(ExportEntity)

int ExportEntity::process()
{
	int res = 0;

	param_string(dbid);
	param_string(name);
	param_string(format);
	
	webx::CheckFileName(name);
	webx::CheckSystemRight(this);

	sp<DBConnect> dbconn = webx::GetDBConnect(dbid);
	sp<QueryResult> result = dbconn->query("SELECT * FROM " + name + " WHERE 1=0");

	if (!result) stdx::Throw(XG_ERROR, dbconn->getErrorString());

	res = result->cols();

	if (res > 0)
	{
		string line;
		string source;
		ColumnData item;

		if (stdx::tolower(format) == "list")
		{
			JsonElement arr = json.addArray("list");

			for (int i = 0; i < res; i++)
			{
				JsonElement data = arr[i];

				if (result->getColumnData(item, i))
				{
					string type = stdx::tolower(item.getTypeString()).substr(2);

					data["type"] = type;
					data["name"] = item.name;
					data["size"] = item.size;
					data["scale"] = item.scale;
					data["nullable"] = item.nullable;
				}
			}
		}
		else
		{
			for (int i = 0; i < res; i++)
			{
				if (result->getColumnData(item, i))
				{
					string name = item.name;
					string oper = item.nullable ? "n" : "r";

					switch(item.type)
					{
						case DBData_Float:
							line = "\t" + oper + "double(" + stdx::tolower(name) + ");\n";
							break;
						case DBData_Integer:
							line = "\t" + oper + "int(" + stdx::tolower(name) + ");\n";
							break;
						default:
							line = "\t" + oper + "string(" + stdx::tolower(name) + ");\n";
							break;
					}

					source += line;
				}
			}

			stdx::toupper(name);
		
			string cls = "JsonEntity(Entity)";
			string inc = "#include <json/json.h>";
			string gap = "///////////////////////////////////////////////";
			string head = stdx::format("#ifndef XG_DBENTITY_%s_H\n#define XG_DBENTITY_%s_H", name.c_str(), name.c_str());

			source = stdx::format("%s\n%s\n%s\n\n%s\n{\npublic:\n%s};\n%s\n#endif",
						head.c_str(), gap.c_str(), inc.c_str(), cls.c_str(),
						source.c_str(), gap.c_str());

			json["content"] = source;
		}
	}

	json["code"] = res;
	out << json;

	return XG_OK;
}